<template>
  <BasicDrawer 
    v-bind="$attrs" 
    @register="registerDrawer" 
    :title="getTitle" 
    width="500px" 
    @ok="handleSubmit" 
    showFooter
    destroyOnClose
  >
    <BasicForm @register="registerForm"/>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { fieldFormSchemas, MsgFieldType } from '../data';
  import { BasicDrawer, useDrawerInner} from '/@/components/Drawer';
  import * as evbApi from '/@/api/infra/eventBus';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ColEx } from '/@/components/Form/src/types';
  const { createMessage } = useMessage();

  const emit = defineEmits(['success', 'register']);
  const attrs = useAttrs()
  const isUpdate = ref(true);
  const record = ref<any>({});

  const [registerForm, {setProps, resetFields, setFieldsValue, validate, updateSchema}] = useForm({
    labelWidth: 90,
    schemas: fieldFormSchemas,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  });
  
  const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
    await resetFields();
    record.value = data.record || {}
    console.log('record:', record.value)
    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      isUpdate.value = !!data?.isUpdate;
      await setFieldsValue({ 
        ...record.value
      })

      updateSchema([
        {
          field: 'fieldType',
          componentProps: {
            placeholder: "请选择",
            allowClear: true,
            showSearch: true,
            filter: (item) => {
              // 规定数组中不能嵌套数组
              return record.value.parentFieldType != MsgFieldType.ARRAY || item != MsgFieldType.ARRAY
            },
            dictType: "evb_msgFieldType",
          },
        }
      ])
    } finally {
      setDrawerProps({ loading: false})
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增字段' : '编辑字段'));

  async function handleSubmit() {
    try {
      let values = await validate();
      setDrawerProps({confirmLoading: true});

      await evbApi.saveOrUpdateTopicMsgField({...values}, unref(isUpdate));
      closeDrawer();
      createMessage.success(`${getTitle.value}成功`)
      emit('success');
    } finally {
      setDrawerProps({confirmLoading: false});
    }
  }
</script>
